/**
 *订单支付
 */
$(function() {
	// 绑定事件
	$(window).on("load", queyrOrderDetail);
	$('.pay-sumbit').on("tap", submitOrder);

	var $orderType = utilModule.getQueryString("orderType");

	// 封装form对象Vo
	function OrderVo() {
		var orderVo;
		orderVo = utilModule.dealFormFilter('payForm');
		return orderVo;
	}

	//查询订单明细
	function queyrOrderDetail() {
		var orderid = utilModule.getQueryString("orderid");
		var orderType = utilModule.getQueryString("orderType");
		if(utilModule.checkUndefined(orderid) == "") {
			mui.alert("参数id不能为空", "提示");
			return false;
		}
		var params = {
			id: orderid
		};
		var orderInfo = null;
		if(orderType == 1) {
			queryTextOrderDetail(params);
		} else if(orderType == 5) {
			queryMallOrderDetail(params);
		} else {
			queryPhoneOrderDetail(params);
		}
	}
	//对比账户余额和订单总价值
	function comparative() {
		var totalAcount = $("#totalAcount").val(); //账户余额值
		var orderMoney = $("#payamount").val(); //订单价格
		var comparativePayment = parseFloat(totalAcount) - parseFloat(orderMoney);
		console.log(comparativePayment);

		if($orderType == 1 && comparativePayment >= 0) {
			$("#accountBalance").attr("checked", true);
			$("#WeChatpayment").attr("checked", false);
		}
		if($orderType == 2 || $orderType == 5) {
			$(".recharge_icon2").parent().hide();
		}
		if(comparativePayment = NaN) {
			$(".payamount").html = "";
		}
	}

	//初始化数据
	function initData(orderInfo) {
		console.log(orderInfo);
		if(orderInfo != null) {
			$("#id").val(orderInfo.id);
			$("#ordersn").val(orderInfo.ordersn);
			$(".ordersn").text(orderInfo.ordersn);
			$("#payamount").val(orderInfo.payamount);
			$(".payamount").html("¥" + orderInfo.payamount+"元");
			$(".order-total span").text("¥" + orderInfo.payamount+"元");
			//如果是电话咨询订单，需要初始化以下数据
			$("#doctorid").val(orderInfo.doctorid);
			$(".serviceTime").text(orderInfo.createtime);
			var serviceTime = orderInfo.serviceTime;
			var answerPhone = orderInfo.answerPhone;
			$("#serviceTime").val(orderInfo.serviceTime);
			$("#answerPhone").val(orderInfo.answerPhone);
			
			if(utilModule.checkUndefined(answerPhone) != "") {
				$("#answerPhone").val(answerPhone);
			}

			//初始化医生详情
			var orderDetail = orderInfo.orderDetail;
			if(orderDetail != null) {
				var _info = orderDetail.split(":");
				$("#directive-doctor").text(_info[0]);
				$(".directive-doctor").text(_info[0]);
				$("#rank-hospital").text(_info[1]);
				$("#orderDetail").val(_info[0]);
				$("#showFeeDiv").html(orderInfo.payamount.toFixed(2) + "/次");
			}
			$("#payAmountDiv").html(orderInfo.payamount.toFixed(2));
		}

		initUserInfo();
		comparative();

	}

	//查询电话订单明细
	function queryPhoneOrderDetail(params) {
		orderPayModule.queryPhoneOrderDetail(params,
			function(callBack) {
				var orderInfo = callBack;
				if(orderInfo != null) {
					orderInfo.payamount = orderInfo.price;
					orderInfo.orderType = 2;
					initData(orderInfo);
				}
			});
	}

	//查询图文订单明细
	function queryTextOrderDetail(params) {
		orderPayModule.queryOrderDetail(params,
			function(callBack) {
				var orderInfo = callBack;
				if(orderInfo != null) {
					initData(orderInfo);
					//初始化问题内容,仅图文咨询使用
					$("#questionbody").val(orderInfo.questionbody);
					$("#ext").val(orderInfo.membersex + ":" + orderInfo.memberbirthday);
				}
			});

	}

	//查询购药订单明细
	function queryMallOrderDetail(params) {
		orderPayModule.queryMallOrderDetail(params,
			function(callBack) {
				var orderInfo = callBack;
				if(orderInfo != null) {
					orderInfo.payamount = orderInfo.goodsAmount;
					orderInfo.createtime = orderInfo.addTime;//TODO:
					orderInfo.orderDetail = "药品费用";//TODO:
					initData(orderInfo);
				}
			});
	}

	// 查看账户明细
	function initUserInfo() {
		var params = {
			"userid": USERID
		};
		userCenterModule.queryUserInfo(params, function(callBack) {
			var userInfo = callBack;
			if(userInfo.accountbalance != null) {
				$("#showPriceDiv").html("当前账户余额￥" + userInfo.accountbalance.toFixed(2));
			}
			$("#totalAcount").val(userInfo.accountbalance);
		});
	}

	//支付成功，跳转聊天界面
	function invokeIm() {
		var orderid = utilModule.getQueryString("orderid");

		var params = {
			"doctorId": $("#doctorid").val()
		};
		var doctorIm = "";

		var payStatus = $("#payamount").val() == 0.00 ? 0 : 1; //免費咨詢	

		doctorModule.queryDetail(params, function(callBack) {
			var result = callBack;
			if(result != null) {
				var doctorInfo = result.doctor;
				//doctor_user_20
				var doctorObject = {};
				doctorObject.doctorid = doctorInfo.id;
				var usernameIM = DOCTOR_IM_PREFFIX + doctorInfo.id;
				var questionbody = $("#questionbody").val(); //提问内容
				var ext = $("#ext").val(); //扩展字段
				doctorObject.usernameIM = usernameIM;
				doctorObject.avatar = doctorInfo.avatar;
				doctorObject.realname = doctorInfo.realname;
				doctorObject.deptName = doctorInfo.deptName;
				doctorObject.questionbody =
					utilModule.setStorage(usernameIM, JSON.stringify(doctorObject));
				mui.toast("支付成功，正在跳转咨询界面....");
				console.log("医生信息:" + utilModule.getStorage(usernameIM));

				//清空与该医生之前的聊天记录
				var chatList = utilModule.getStorage("chat_list");
				if(chatList != null) {
					var chatObject = JSON.parse(chatList);

					var rd_key = DOCTOR_IM_PREFFIX + doctorInfo.id;
					delete chatObject[rd_key];

					var $chatObject = JSON.stringify(chatObject);

					utilModule.setStorage("chat_list", $chatObject);

				}

				//支付成功跳转im聊天界面 payStatus: 2:图文订单+'&doctorid='+obj.doctorid+'
				var toImUrl = "../inquiry/inquiry-service.html?usernameIM=" + usernameIM + "&orderid=" + orderid + "&payStatus=2&doctorid=" + doctorInfo.id;
				toImUrl += "&msg=" + encodeURIComponent(questionbody) + "&ext=" + ext;
				location.replace(toImUrl);
			}
		});
	}

	// 提交支付
	function submitOrder() {
		var orderVo = OrderVo();
		orderVo.userid = USERID;
		orderVo.openid = OPENID;
		var payType = $("input[name=payType]:checked").val();
		orderVo.payType = payType;
		var id = $("#id").val();
		var orderType = utilModule.getQueryString("orderType") == "" ? 2 : utilModule.getQueryString("orderType");
		var orderId = utilModule.getQueryString("orderid");
		if(orderType == 1) {
			submitTextOrderPay(orderVo);
			//location.replace("../../html/onlineContinuation/pay-success.html?orderType=1&orderid="+orderId);
		} else if(orderType == 5) {
			submitMallOrderPay(orderVo);
			//location.replace("../../html/onlineContinuation/pay-success.html?orderType=5&orderid="+orderId);
		} else {
			submitPhoneOrderPay(orderVo);
			
		}

	}

	//提交图文订单支付
	function submitTextOrderPay(orderVo) {
		var totalAcount = $("#totalAcount").val(); //账户余额
		var orderMoney = $("#payamount").val(); //订单价格
		var payType = orderVo.payType;
		if(orderMoney == 0.00) {
			//return invokeIm(); //免费直接进入聊天界面
			location.replace("../inquiry/message-list.html");
		}
		if(payType == 2 && parseFloat(totalAcount) < parseFloat(orderMoney)) {
			mui.alert('账户余额不足，请选择其它支付方式', '提示');
			return false;
		} else {
			orderPayModule.submitPayOrder(orderVo,
				function(callBack) {
					var payInfo = callBack;
					if(payInfo != null) {
						var orderId = utilModule.getQueryString("orderid");
						if(payType == 1) {
							onBridgeReady(payInfo);
						} else {
							//invokeIm();  //余额支付成功直接跳转Im界面
							location.replace("../../html/onlineContinuation/pay-success.html?orderType=1&orderid="+orderId);
						}

					}

				});
		}

	}

	//提交电话咨询支付
	function submitPhoneOrderPay(orderVo) {
		/*var totalAcount = $("#totalAcount").val();*/
		var orderMoney = $("#payamount").val();
		var payType = orderVo.payType;
		/*if(payType == 2 && parseFloat(totalAcount) < parseFloat(orderMoney)) {
			mui.alert('账户余额不足，请选择其它支付方式', '提示');
			return false;
		} else {*/
		orderVo.price = orderMoney;
		orderPayModule.submitPhonePayOrder(orderVo,
			function(callBack) {
				console.log(callBack);
				var payInfo = callBack;
				if(payInfo != null) {
					var orderId = utilModule.getQueryString("orderid");
					if(payType == 1) {
						onBridgeReady(payInfo);
						//location.replace("../../html/rapidly-phone/rapidly-detail.html?orderType=3&orderid="+orderId);
					} else {
						//submitSuccess();
						location.replace("../../html/rapidly-phone/rapidly-detail.html?orderType=3&orderid="+orderId);
					}

				}

			});
		/*}*/

	}

	//提交购药订单
	function submitMallOrderPay(orderVo) {
		var orderMoney = $("#payamount").val();
		var payType = orderVo.payType;
		orderVo.price = orderMoney;
		orderPayModule.submitMallPayOrder(orderVo,
			function(callBack) {
				console.log(callBack);
				var payInfo = callBack;
				if(payInfo != null) {
					onBridgeReady(payInfo);
				    //var orderId = utilModule.getQueryString("orderid");
					//location.replace("../../html/onlineContinuation/pay-success.html?orderType=5&orderid="+orderId);
				}

		});

	}

	//电话咨询支付成功
	function submitSuccess() {
		var answerPhone = $("#answerPhone").val();
		var serviceTime = $("#serviceTime").val();
		var $doctorid = $("#doctorid").val();
		var showTitle = "恭喜您，预约成功!您预约的接听时间为:" + serviceTime + ",<br>接听号码为:" + answerPhone + "";
		mui.alert(showTitle, "提示", function() {
			orderPayModule.pushMessage({
				doctorid: $doctorid
			}, function(callBack) {});
			
		});

	}

	// 发起微信支付
	function onBridgeReady(result) {
		WeixinJSBridge.invoke('getBrandWCPayRequest', {
			"appId": result.appId, // 公众号名称，由商户传入
			"timeStamp": result.timeStamp, // 时间戳，自1970年以来的秒数
			"nonceStr": result.nonceStr, // 随机串
			"package": result.package, //package
			"signType": result.signType, // 微信签名方式：
			"paySign": result.paySign // 微信签名
		}, function(res) {
			if(res.err_msg == "get_brand_wcpay_request:ok") {
				var orderId = utilModule.getQueryString("orderid");
				if($orderType == 1) {
					//invokeIm(); //进入聊天界面
					var orderId = utilModule.getQueryString("orderid");
					location.replace("../../html/onlineContinuation/pay-success.html?orderType=1&orderid="+orderId);
				} else if($orderType == 5) {
					//TODO：跳转订单中心列表页面
					var orderId = utilModule.getQueryString("orderid");
					//location.href = "../../html/onlineContinuation/my-order.html?shipping_status=5";
					location.replace("../../html/onlineContinuation/pay-success.html?orderType=5&orderid="+orderId);
					//return false;
				} else if($orderType == 2)  {
					var orderId = utilModule.getQueryString("orderid");
					//submitSuccess(); //电话咨询支付成功
					//var orderId = utilModule.getQueryString("orderid");
					location.replace("../../html/rapidly-phone/rapidly-detail.html?orderType=3&orderid="+orderId);
				}
			} else if(res.err_msg == "get_brand_wcpay_request:cancel") {
				mui.alert('取消支付！', '提示');
			} else {
				mui.alert('支付失败！', '提示');
			}
		});
	}

});